package br.com.acs.CameraIP.dao;

import br.com.acs.CameraIP.model.Cliente;

import br.com.acs.CameraIP.util.HibernateUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import org.hibernate.Session;
import org.hibernate.Transaction;
 
public class ClienteDaoImp implements ClienteDao {
 
    public void save(Cliente cliente) {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = session.beginTransaction();
        session.merge(cliente);
        t.commit();
    }
    public Cliente getCliente(long id) {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    	//Transaction t = session.beginTransaction();
    	//t.commit();
        return (Cliente) session.load(Cliente.class, id);
    }
	
    @SuppressWarnings("unchecked")
	public List<Cliente> listTodos() {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = session.beginTransaction();
        List<Cliente> lista = session.createQuery("from Empresa order by razaoSocial").list();
        t.commit();
        return lista;
    }
    
   
    @SuppressWarnings("unchecked")
	public List<Cliente> listAtivos() {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = session.beginTransaction();
        List<Cliente> lista = session.createQuery("from Empresa where ativo = 'S' order by razaoSocial").list();
        t.commit();
        return lista;
    }
    
    @SuppressWarnings("unchecked")
	public List<Cliente> PrimeiroClienteCadastrado() {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = session.beginTransaction();
        String SQL_QUERY = "Select last_insert_id(id) from Empresa where ativo = 'S' order by id desc limit 1";
        System.out.println(SQL_QUERY);
        List<Cliente> lista = session.createSQLQuery(SQL_QUERY).list();
        List<Cliente> lista2 = new ArrayList<Cliente>();
        for (Iterator<?> it = lista.iterator(); it.hasNext();) {
           Object[] row = (Object[]) it.next();
          
           Cliente empresa = new Cliente();
           empresa.setIdClienteSelecionado((Long)row[0]);
           lista2.add(empresa);  
       }
       
       t.commit();
       return lista2;
    }
    
    public void remove(Cliente cliente) {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = session.beginTransaction();
        session.delete(cliente);
        t.commit();
    }
    public void update(Cliente cliente) {
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction t = session.beginTransaction();
        session.update(cliente);
        t.commit();
    }

    
}

